<template>
  <div>
    <div class="main">

      <div class="overview">班级平均年龄:{{ avgAge }}</div>

      <div class="tools-header">
        <div>
          <button class="openModalBtn" @click="addStudent">Add New Student</button>
          <button class="openModalBtn" @click="delSelectedStudent">Del New Student</button>
          <button class="openModalBtn" @click="stusave">Save</button>
        </div>
        <div>
          <input v-model.trim="keyword" type="text" name="keyword" class="keyword" placeholder="Search by name" />
          <button @click="generateSearchData" type="button" class="searchBtn">Search</button>
        </div>
      </div>

      <table class="studentTable">
        <thead>
          <tr>
            <th><input v-model="isAllSelected" @change="changeSelectedAll" type="checkbox" class="selectAll" /></th>
            <th>ID</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Hobbies</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Age</th>
            <th>Created At</th>
            <th>Updated At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <!-- Student rows will be added dynamically here -->
          <tr v-for="item in searchStudentArr" :key="item.id">
            <td>
              <input @change="changeSeletedItem" v-model="item.seleted" type="checkbox" class="selectAll selectitem">
            </td>
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.gender }}</td>
            <td>{{ item.hobbies }}</td>
            <td>{{ item.email }}</td>
            <td>{{ item.phone }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.create_at }}</td>
            <td>{{ item.update_at }}</td>
            <td>
              <a class="tda" href="javascript:void(0)" @click="editStuInfo(item)">修改</a>
              <a class="tda" href="javascript:void(0)" @click="removeStuInfo(item)">删除</a>
            </td>

          </tr>

        </tbody>
      </table>

      <!-- Modal for adding/editing students -->
      <div v-show="isShowModel" class="studentModal modal" @click="closeModel">
        <div class="modal-content" @click.stop>
          <h3 class="modalTitle">{{ modelInfo.title }}</h3>
          <form class="studentForm">
            <input v-model="stuFormData.id" type="hidden" class="studentIdToEdit" />

            <label for="studentName">Name</label>
            <input v-model="stuFormData.name" type="text" name="name" class="studentName" required />

            <label for="studentGender">Gender</label>
            <select v-model="stuFormData.gender" name="gender" class="studentGender" required>
              <option value="Male">Male</option>
              <option value="Female">Female</option>
            </select>

            <label for="studentHobbies">Hobbies</label>
            <input v-model="stuFormData.hobbies" type="text" name="hobbies" class="studentHobbies" required />

            <label for="studentEmail">Email</label>
            <input v-model="stuFormData.email" type="email" name="email" class="studentEmail" required />

            <label for="studentPhone">Phone</label>
            <input v-model="stuFormData.phone" type="text" name="phone" class="studentPhone" required />

            <label for="studentAge">Age</label>
            <input v-model="stuFormData.age" type="number" name="age" class="studentAge" required />

            <button @click.prevent="saveStuInfo" @click="closeModel" type="submit" class="saveStudentBtn">Save
              Student</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getNowDateTime } from '@/utils';
import { computed, ref, unref, } from 'vue';
import { iteratee, rangeRight, remove, uniqueId } from 'lodash';

interface IStudent {
  id: string
  name: string
  gender: string
  hobbies: string
  email: string
  phone: string
  age: number | string
  create_at: string
  update_at: string
  seleted?: boolean
}

const modelInfo = ref({
  type: 'add',
  title: '添加学生信息'
})
const keyword = ref('')

const isAllSelected = ref(false)

const stuFormData = ref<IStudent>({
  id: '',
  name: '',
  gender: '',
  hobbies: '',
  email: '',
  phone: '',
  age: '',
  create_at: getNowDateTime(),
  update_at: getNowDateTime()

})

const student = localStorage.getItem('student') as string;
const studentArr: Array<IStudent> = JSON.parse(student);


// const studentArr: Array<IStudent> = [
//   {
//     id: '1',
//     name: 'Alice',
//     gender: 'Female',
//     hobbies: 'Reading',
//     email: 'alice@example.com',
//     phone: '12345678901',
//     age: 20,
//     create_at: getNowDateTime(),
//     update_at: getNowDateTime()
//   },
//   {
//     id: '2',
//     name: 'Bob',
//     gender: 'Male',
//     hobbies: 'Sports',
//     email: 'bob@example.com',
//     phone: '10987654321',
//     age: 22,
//     create_at: getNowDateTime(),
//     update_at: getNowDateTime()
//   },
//   {
//     id: '3',
//     name: "Charlie",
//     gender: "Male",
//     hobbies: "Gaming",
//     email: "charlie@example.com",
//     phone: "19876543210",
//     age: 25,
//     create_at: getNowDateTime(),
//     update_at: getNowDateTime()
//   },
//   {
//     id: '4',
//     name: "Diana",
//     gender: "Female",
//     hobbies: "Traveling",
//     email: "diana@example.com",
//     phone: "123098765432",
//     age: 28,
//     create_at: getNowDateTime(),
//     update_at: getNowDateTime()
//   }
// ]


const searchStudentArr = ref<Array<IStudent>>([])

const generateSearchData = () => {
  searchStudentArr.value = studentArr.filter((i) => i.name.includes(keyword.value))
}

const initAction = () => {
  generateSearchData()
}

const saveStuInfo = () => {
  if (modelInfo.value.type === 'add') {
    stuFormData.value.id = `${studentArr.length + 1}`;
    // uniqueId(`${studentArr.value.length + 1}`)
    console.log(stuFormData.value)
    studentArr.push(JSON.parse(JSON.stringify(stuFormData.value)))
  } else if (modelInfo.value.type === 'edit') {
    const index = studentArr.findIndex(student => student.id === stuFormData.value.id);
    studentArr[index] = (JSON.parse(JSON.stringify(stuFormData.value)))
    studentArr[index].update_at = getNowDateTime()
    modelInfo.value.type = 'add'
  }
  generateSearchData()
  stusave()
}


const isShowModel = ref(false)

const addStudent = () => {
  stuFormData.value = {
    id: '',
    age: '',
    email: '',
    gender: '',
    hobbies: '',
    name: '',
    phone: '',
    create_at: getNowDateTime(),
    update_at: getNowDateTime()
  }
  modelInfo.value.type = 'add'
  modelInfo.value.title = '添加学生信息'
  isShowModel.value = true
}
const editStuInfo = (stu: IStudent) => {
  modelInfo.value.type = 'edit'
  modelInfo.value.title = '修改学生信息'
  stuFormData.value = JSON.parse(JSON.stringify(stu))
  isShowModel.value = true
}

const removeStuInfo = (stu: IStudent) => {
  const index = studentArr.findIndex(student => student.id === stu.id);
  studentArr.splice(index, 1);
  generateSearchData()
  stusave()
};

const delSelectedStudent = () => {
  searchStudentArr.value.forEach((item: IStudent) => {
    if (item.seleted === true) {
      removeStuInfo(item)
    }
  })
}

const changeSelectedAll = (event: Event) => {
  const checked = (event.target as HTMLInputElement).checked
  console.log(checked, 'checked')

  if (checked) {
    searchStudentArr.value.forEach((item: IStudent) => {
      item.seleted = true
    })
  } else {
    searchStudentArr.value.forEach((item: IStudent) => {
      item.seleted = false
    })
  }
}

const changeSeletedItem = () => {
  isAllSelected.value = searchStudentArr.value.every((i) => i.seleted)
}


const closeModel = () => {
  isShowModel.value = false
}

const avgAge = computed(() => {
  return studentArr.reduce((acc, student) => {
    return acc + Number(student.age);
  }, 0) / studentArr.length;
});

const stusave = () => {
  localStorage.setItem('student', JSON.stringify(studentArr));
}



initAction()
</script>

<style lang="scss" scoped>
@import './style/demo1.scss';
</style>
